package cn.nexttec.noteplayer.ui.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import cn.nexttec.noteplayer.R

data class TabItem(val title: String, val iconResId: Int)

class SlantedTabView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : LinearLayout(context, attrs) {

    private var selectedIndex = 0
    private var tabItems = listOf<TabItem>()
    private var tabClickListener: ((Int) -> Unit)? = null

    // Custom attributes
    private var selectedBgColor = Color.WHITE
    private var unselectedBgColor = Color.LTGRAY
    private var selectedTextColor = Color.BLACK
    private var unselectedTextColor = Color.DKGRAY
    private var textSizeSp = 14f
    private var tabWidth = 120.dpToPx()
    private var tabHeight = 48.dpToPx()
    private var iconSize = 30.dpToPx()

    init {
        orientation = HORIZONTAL
        gravity = Gravity.CENTER_VERTICAL

        attrs?.let {
            val ta = context.obtainStyledAttributes(it, R.styleable.SlantedTabView)
            selectedBgColor = ta.getColor(R.styleable.SlantedTabView_selectedBackgroundColor, selectedBgColor)
            unselectedBgColor = ta.getColor(R.styleable.SlantedTabView_unselectedBackgroundColor, unselectedBgColor)
            selectedTextColor = ta.getColor(R.styleable.SlantedTabView_selectedTextColor, selectedTextColor)
            unselectedTextColor = ta.getColor(R.styleable.SlantedTabView_unselectedTextColor, unselectedTextColor)
            textSizeSp = ta.getDimension(R.styleable.SlantedTabView_textSize, textSizeSp.spToPx()).pxToSp()
            tabWidth = ta.getDimensionPixelSize(R.styleable.SlantedTabView_tabWidth, tabWidth)
            tabHeight = ta.getDimensionPixelSize(R.styleable.SlantedTabView_tabHeight, tabHeight)
            iconSize = ta.getDimensionPixelSize(R.styleable.SlantedTabView_iconSize, iconSize)
            ta.recycle()
        }
    }

    fun setTabs(
        tabs: List<TabItem>,
        onTabSelected: (Int) -> Unit
    ) {
        this.tabItems = tabs
        this.tabClickListener = onTabSelected
        buildTabs()
    }

    private fun buildTabs() {
        removeAllViews()
        tabItems.forEachIndexed { index, item ->
            val tabLayout = LinearLayout(context).apply {
                orientation = HORIZONTAL
                gravity = Gravity.CENTER
                background = SlantedTabDrawable(
                    if (index == selectedIndex) selectedBgColor else unselectedBgColor
                )
                val params = if (tabWidth <= 0) {
                    LayoutParams(0, tabHeight, 1f) // 平均分配宽度
                } else {
                    LayoutParams(tabWidth, tabHeight)
                }.apply {
                    marginEnd = -40
                }
                layoutParams = params
                elevation = if (index == selectedIndex) 8f else 0f
                setOnClickListener {
                    updateSelected(index)
                    tabClickListener?.invoke(index)
                }
            }

            val iconView = ImageView(context).apply {
                setImageResource(item.iconResId)
                layoutParams = LayoutParams(iconSize, iconSize)
            }

            val textView = TextView(context).apply {
                text = item.title
                gravity = Gravity.CENTER
                setTextSize(TypedValue.COMPLEX_UNIT_SP, textSizeSp)
                setTextColor(if (index == selectedIndex) selectedTextColor else unselectedTextColor)
                setPadding(8.dpToPx(), 0, 0, 0) // 加一点左边距
            }

            tabLayout.addView(iconView)
            tabLayout.addView(textView)
            addView(tabLayout)
        }
    }

    private fun updateSelected(newIndex: Int) {
        if (newIndex == selectedIndex) return

        for (i in 0 until childCount) {
            val tabLayout = getChildAt(i) as LinearLayout
            val selected = i == newIndex

            // 设置背景
            tabLayout.background = SlantedTabDrawable(
                if (selected) selectedBgColor else unselectedBgColor
            )
            tabLayout.elevation = if (selected) 8f else 0f

            // 找到 TextView 并设置文字颜色
            for (j in 0 until tabLayout.childCount) {
                val child = tabLayout.getChildAt(j)
                if (child is TextView) {
                    child.setTextColor(
                        if (selected) selectedTextColor else unselectedTextColor
                    )
                }
            }
        }

        selectedIndex = newIndex
    }


    // Draws slanted tab with rounded top-right corner and slanted right edge
    class SlantedTabDrawable(private val bgColor: Int) : Drawable() {
        private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
            style = Paint.Style.FILL
            color = bgColor
        }

        override fun draw(canvas: Canvas) {
            val w = bounds.width().toFloat()
            val h = bounds.height().toFloat()

            val path = Path().apply {
                moveTo(0f, 0f)
                lineTo(w - 30f, 0f)
                quadTo(w, 0f, w, 20f) // top-right curve
                lineTo(w, h)
                lineTo(0f, h)
                close()
            }

            canvas.drawPath(path, paint)
        }

        override fun setAlpha(alpha: Int) {
            paint.alpha = alpha
        }

        override fun setColorFilter(colorFilter: ColorFilter?) {
            paint.colorFilter = colorFilter
        }

        override fun getOpacity(): Int = PixelFormat.OPAQUE
    }



    // --- Unit conversion helpers ---
    private fun Int.dpToPx(): Int =
        (this * resources.displayMetrics.density).toInt()

    private fun Float.spToPx(): Float =
        this * resources.displayMetrics.scaledDensity

    private fun Float.pxToSp(): Float =
        this / resources.displayMetrics.scaledDensity
}



